package org.git.movie.videojiexi.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.git.movie.videojiexi.enums.VideoChannel;
import org.git.movie.videojiexi.model.VideoModel;
import org.git.movie.videojiexi.service.VideoService;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.springframework.stereotype.Service;



import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLDecoder;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**  
* @comment
* @author tanran 
* @date 2019年6月14日  
* @version 1.0  
*/
@Service(value = "KuaiShouServiceImpl")
public class KuaiShouServiceImpl implements VideoService {


	@Override
	public VideoModel parseUrl(String url, String userAgent) throws Exception {
		Map<String, String> headers = new HashMap<>();
		headers.put("Connection", "keep-alive");
		userAgent = "Mozilla/5.0 (iPhone; CPU iPhone OS 12_1_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/16D57 Version/12.0 Safari/604.1";

		headers.put("User-Agent", userAgent);

		//6.利用Joup获取视频对象,并作封装成一个输入流对象
		String html = Jsoup.connect(url).headers(headers).timeout(10000).ignoreContentType(true).execute().body();
		//System.out.println(html);
		Document doc = Jsoup.parse(html);
		Element div = doc.selectFirst("div[id=hide-pagedata]");
		String data_pagedata = div.attr("data-pagedata");
		String decodeData = URLDecoder.decode(data_pagedata,"utf-8");
		//System.out.println(decodeData);
		JSONObject videoInfo = JSON.parseObject(decodeData);

		String photoId = videoInfo.getString("photoId");
		JSONObject video = videoInfo.getJSONObject("video");

		String matchUrl = video.getString("src");
		String picUrl = video.getString("poster");
		String fileType = video.getString("fileType");

		VideoModel rep = new VideoModel();
		rep.setCover(picUrl);
		rep.setFileType(fileType);
		rep.setPlayAddr(matchUrl);
		rep.setChannel(VideoChannel.KUAISHOU);

		return rep;
	}



	public static void main(String[] args) throws Exception {
		String url = "https://kphshanghai.m.chenzhongtech.com/s/cRpTnwYj";
		url = "https://kphbeijing.m.chenzhongtech.com/s/JfYXg8sC";
		VideoModel rep = new KuaiShouServiceImpl().parseUrl(url,null);
		System.out.println(JSON.toJSONString(rep));
	}




}
